<?php
/**
 * Display Partners List
 */

use Fox\MaterialManagement\Material;
use Doctrine\DBAL\Connection;

$ajax = Xview::instance()->val("xvtrs");
$tree = Xview::instance()->component("material", "components")->item("tComponents"); 
$id = Xview::instance()->val("materialid");

if(!empty($ajax))
{
	$root = new Fox\Node(Fox\Node::ROOT_NODE);
	$uniqueData = null;
	$data = $tree->get();
	if(is_array($data))
	{
		foreach($data as $key => $line)
		{
			if(empty($line['componentid']))
				continue;

			if(isset($treeData[$line['materialid']]))
			{
				$treeData[$line['componentid']] = $treeData[$line['materialid']]->add(new Fox\Node($line));
			}
			else
			{
				$treeData[$line['componentid']] = $root->add(new Fox\Node($line));
			}
			
		}
	}
	$codes = Xview::instance()->val("codes");
	if(is_array($codes))
	{
		$finder = new Material();
		$materials = $finder->find(new Fox\Dao\SqlFragment("materialid IN (?)",array($codes),array(Connection::PARAM_INT_ARRAY)));
		foreach($materials as $material)
		{
			$data = $material->getData();
			$data['componentid'] = $material->getId();
			$data['materialid'] = $id;
			$data['quantity'] = 1;
			$data['position'] = 1;
			if(isset($treeData[$data['componentid']]))
				continue;
			
			$treeData[$data['componentid']] = $root->add(new Fox\Node($data));
			
		}
	}
	$tree->setDatas($root);
	echo $tree->Display();
}